package com.wyz.saas.api.core

import java.util.*

open class Observable<T> : IObservable<T> {

    private val observers  = hashSetOf<IObserver<T>>()

    override fun addObserver(observer: IObserver<T>) {
        synchronized(observers) {
            observers.add(observer)
        }
    }

    override fun removeObserver(observer: IObserver<T>): Boolean {
        synchronized(observers) {
            return observers.remove(observer)
        }
    }

    override fun clearObserver(): Set<IObserver<T>> {
        var unmodifiableList: Set<IObserver<T>>
        synchronized(observers) {
            unmodifiableList = Collections.unmodifiableSet(observers)
            observers.clear()
        }
        return unmodifiableList
    }

    override fun notify(state: State, type: Collection<T>, throwable: Throwable?) {
        synchronized(observers) {
            observers.forEach { it.run(state, type, throwable) }
        }
    }
}